package br.com.cefetrn.apoena.view.action;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import br.com.cefetrn.apoena.dominio.entity.Login;
import br.com.cefetrn.apoena.view.component.HibernateSession;
import br.com.cefetrn.apoena.view.component.HibernateSessionAware;

import com.opensymphony.xwork.ActionSupport;
import com.opensymphony.xwork.Preparable;

public abstract class AxActionAPOENA extends ActionSupport implements InfcCRUD, Preparable, HibernateSessionAware{
	
	private static final Log LOG = LogFactory.getLog(AxActionAPOENA.class);
	
	/** 
	 * Parametro informado para CRUD, tipo de ação. 
	 * 
	 */
	protected String tipo = "";
	
	/**
	 * Para todas as subactions.
	 */
	protected String result = ActionSupport.SUCCESS;
	
	protected String botao = "";
	
	private HibernateSession session;
	
	public void prepare() throws Exception {}
	
	public String execute() throws Exception {
		
		LOG.info("executing action");
		
		// We go to INPUT on field and data errors
		if (hasErrors()) {
			
			LOG.info("action not executed, field or action errors");
			LOG.info("Field errors: " + getFieldErrors());
			LOG.info("Action errors: " + getActionErrors());
			
			return INPUT;
		}
		
		try {
			
			return go();
			
		} catch (Exception e) {
			LOG.error("action - ", e);
			throw e;
		}
	}

	protected abstract String go();
	
	public void setHibernateSession(HibernateSession session) {
		LOG.debug("seting HibernateSession");
		this.session = session;
	}
	
	public HibernateSession getHibernateSession() {
		LOG.debug("geting HibernateSession");
		return session;
	}
	
	/**
	 * Get the Hibernate Session instance
	 */
	public Session getSession() throws HibernateException {
		LOG.debug("geting Session");
		return session.getSession();
	}

	protected void setRollbackOnly() {
		session.setRollBackOnly(true);
	}

	public String getTipo() {
		return tipo;
	}

	public void setTipo(String tipo) {
		this.tipo = tipo;
	}

	public String getBotao() {
		return botao;
	}

	public void setBotao(String botao) {
		this.botao = botao;
	}
	
	protected Login criaLogin(){
		Login login = new Login();
		login.setLogin("root");
		login.setSenha("123");
		return login;
	}
	
}
